package org.jeecg.modules.demo.crm.controller;

import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.query.QueryRuleEnum;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.crm.dto.AdditionalStatusCount;
import org.jeecg.modules.demo.crm.entity.CAdditionalRequest;
import org.jeecg.modules.demo.crm.mapper.CAdditionalRequestMapper;
import org.jeecg.modules.demo.crm.mapper.CProjectQuoteMapper;
import org.jeecg.modules.demo.crm.mapper.CQuotationMapper;
import org.jeecg.modules.demo.crm.mapper.CSubProjectMapper;
import org.jeecg.modules.demo.crm.service.ICAdditionalRequestService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.demo.crm.service.ICCommonService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

 /**
 * @Description: 增项需求表
 * @Author: jeecg-boot
 * @Date:   2025-06-18
 * @Version: V1.0
 */
@Api(tags="增项需求表")
@RestController
@RequestMapping("/crm/cAdditionalRequest")
@Slf4j
public class CAdditionalRequestController extends JeecgController<CAdditionalRequest, ICAdditionalRequestService> {
	@Autowired
	private ICAdditionalRequestService cAdditionalRequestService;

	@Autowired
	private CAdditionalRequestMapper cAdditionalRequestMapper;

	@Autowired
	private CProjectQuoteMapper cProjectQuoteMapper;
	 @Autowired
	 private ICCommonService cCommonService;
	 @Autowired
	 private CSubProjectMapper cSubProjectMapper;
	 @Autowired
	 private CQuotationMapper cQuotationMapper;

	/**
	 * 分页列表查询
	 *
	 * @param cAdditionalRequest
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "增项需求表-分页列表查询")
	@ApiOperation(value="增项需求表-分页列表查询", notes="增项需求表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<CAdditionalRequest>> queryPageList(CAdditionalRequest cAdditionalRequest,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 自定义查询规则
        Map<String, QueryRuleEnum> customeRuleMap = new HashMap<>();
        // 自定义多选的查询规则为：LIKE_WITH_OR
        customeRuleMap.put("projectId", QueryRuleEnum.LIKE_WITH_OR);
		customeRuleMap.put("subProjectId", QueryRuleEnum.LIKE_WITH_OR);
        customeRuleMap.put("status", QueryRuleEnum.LIKE_WITH_OR);
		customeRuleMap.put("projectName", QueryRuleEnum.LIKE_WITH_OR);
		customeRuleMap.put("title", QueryRuleEnum.LIKE_WITH_OR);
		customeRuleMap.put("projectNumber", QueryRuleEnum.LIKE_WITH_OR);
		customeRuleMap.put("assignUser", QueryRuleEnum.LIKE_WITH_OR);
		Boolean permissionCheck = cCommonService.permissionCheck();
		if(permissionCheck){
			if("-1".equals(cAdditionalRequest.getProjectId())){
				cAdditionalRequest.setProjectId(null);
			}
			if("-1".equals(cAdditionalRequest.getSubProjectId())){
				cAdditionalRequest.setSubProjectId(null);
			}
			cAdditionalRequest.setAssignUser(sysUser.getId());
		}
		List<String> ids = new ArrayList<>();
		if(cAdditionalRequest.getQuotationStatus()!= null && cAdditionalRequest.getQuotationStatus().length()>0){
			if("已报价".equals(cAdditionalRequest.getQuotationStatus())){
				ids = cQuotationMapper.additionalRelatedQuotation();
			}else if ("未报价".equals(cAdditionalRequest.getQuotationStatus())){
				ids = cQuotationMapper.additionalNotRelatedQuotation();
			}
		}
        QueryWrapper<CAdditionalRequest> queryWrapper = QueryGenerator.initQueryWrapper(cAdditionalRequest, req.getParameterMap(),customeRuleMap);
		if(ids.size()>0){
			queryWrapper.in("id", ids);
		}
		Page<CAdditionalRequest> page = new Page<CAdditionalRequest>(pageNo, pageSize);
		IPage<CAdditionalRequest> pageList = cAdditionalRequestService.page(page, queryWrapper);
		pageList.getRecords().stream().forEach(record -> {
			//报价
			Integer quoteRecord = 0;
			//工程报价
			Integer quotation = 0;
			if(!"admin".equals(sysUser.getRoleCode()) &&
					!"项目经理".equals(sysUser.getRoleCode()) &&
					!"项目负责人".equals(sysUser.getRoleCode())&&
					!"财务出纳".equals(sysUser.getRoleCode()) ){
				quoteRecord = cProjectQuoteMapper.quoteRecordByUserId(sysUser.getId(),record.getId());
			}else {
				quoteRecord = cProjectQuoteMapper.quoteRecord(record.getId());
			}
			quotation = cQuotationMapper.quotationById(record.getId());
			//报价记录
			record.setQuoteRecord(quoteRecord);
			//工程报价
			record.setQuotation(quotation);
		});
		return Result.OK(pageList);
	}

	 @ApiOperation(value="增项需求表-分页列表查询", notes="增项需求表-分页列表查询")
	 @GetMapping(value = "/listAPP")
	 public Result<IPage<CAdditionalRequest>> queryPageAPPList(CAdditionalRequest cAdditionalRequest,
															@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
															@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
															HttpServletRequest req) {
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 Boolean permissionCheck = cCommonService.permissionCheck();
		 // 自定义查询规则
		 Map<String, QueryRuleEnum> customeRuleMap = new HashMap<>();
		 customeRuleMap.put("assignUser", QueryRuleEnum.LIKE_WITH_OR);
		 QueryWrapper<CAdditionalRequest> queryWrapper = QueryGenerator.initQueryWrapper(cAdditionalRequest, req.getParameterMap(),customeRuleMap);
		 if(permissionCheck){
			 queryWrapper.eq("user_id", sysUser.getId());
		 }
		 Page<CAdditionalRequest> page = new Page<CAdditionalRequest>(pageNo, pageSize);
		 IPage<CAdditionalRequest> pageList = cAdditionalRequestService.page(page, queryWrapper);
		 return Result.OK(pageList);
	 }


	
	/**
	 *   添加
	 *
	 * @param cAdditionalRequest
	 * @return
	 */
	@AutoLog(value = "增项需求表-添加")
	@ApiOperation(value="增项需求表-添加", notes="增项需求表-添加")
	@RequiresPermissions("crm:c_additional_request:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody CAdditionalRequest cAdditionalRequest) {

		if(StringUtils.isNotEmpty(cAdditionalRequest.getProjectNumber())){
			int count = cAdditionalRequestMapper.findByProjectNumber(cAdditionalRequest.getProjectNumber());
			if(count>0){
				return Result.error("项目编号重复");
			}
		}
		cAdditionalRequest.setStatus("待处理");
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		cAdditionalRequest.setUserId(sysUser.getId());
		cAdditionalRequestService.save(cAdditionalRequest);
		return Result.OK("添加成功！");
	}

	 /**
	  *   添加
	  *
	  * @param cAdditionalRequest
	  * @return
	  */
	 @AutoLog(value = "增项需求表-添加")
	 @ApiOperation(value="增项需求表-添加", notes="增项需求表-添加")
	 @RequiresPermissions("crm:app:additionalRequestAdd")
	 @PostMapping(value = "/addApp")
	 public Result<String> addApp(@RequestBody CAdditionalRequest cAdditionalRequest) {
		 if(StringUtils.isNotEmpty(cAdditionalRequest.getProjectNumber())){
			 int count = cAdditionalRequestMapper.findByProjectNumber(cAdditionalRequest.getProjectNumber());
			 if(count>0){
				 return Result.error("项目编号重复");
			 }
		 }

		 cAdditionalRequest.setStatus("待处理");
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 cAdditionalRequest.setUserId(sysUser.getId());
		 cAdditionalRequestService.save(cAdditionalRequest);
		 return Result.OK("添加成功！");
	 }


	 @AutoLog(value = "增项需求表-审核")
	 @ApiOperation(value="增项需求表-审核", notes="增项需求表-审核")
	 @RequiresPermissions("crm:c_additional_request:turnDown")
	 @PostMapping(value = "/auditAdditional")
	 public Result<String> auditAdditional(@RequestBody CAdditionalRequest cAdditionalRequest) {
		 CAdditionalRequest byId = cAdditionalRequestService.getById(cAdditionalRequest.getId());
		 if("入库".equals(cAdditionalRequest.getStatus())){
			 byId.setStatus("报价中");
		 }else {
			 byId.setStatus("驳回");
		 }
		 cAdditionalRequestService.updateById(byId);
		 return Result.OK("操作成功！");
	 }


	
	/**
	 *  编辑
	 *
	 * @param cAdditionalRequest
	 * @return
	 */
	@AutoLog(value = "增项需求表-编辑")
	@ApiOperation(value="增项需求表-编辑", notes="增项需求表-编辑")
	@RequiresPermissions("crm:c_additional_request:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody CAdditionalRequest cAdditionalRequest) {
		if(StringUtils.isNotEmpty(cAdditionalRequest.getProjectNumber())){
			int count = cAdditionalRequestMapper.findByProjectNumberAndId(cAdditionalRequest.getProjectNumber(),cAdditionalRequest.getId());
			if(count>0){
				return Result.error("项目编号重复");
			}
		}
		CAdditionalRequest byId = cAdditionalRequestService.getById(cAdditionalRequest.getId());
		cAdditionalRequest.setStatus(byId.getStatus());
		cAdditionalRequest.setAssignUser(byId.getAssignUser());
		cAdditionalRequestService.updateById(cAdditionalRequest);
		return Result.OK("编辑成功!");
	}

	 @AutoLog(value = "增项需求表-指派人")
	 @ApiOperation(value="增项需求表-指派人", notes="增项需求表-指派人")
	 @RequiresPermissions("crm:c_additional_request:assignQuote_edit")
	 @RequestMapping(value = "/assignQuote", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> assignQuote(@RequestBody CAdditionalRequest cAdditionalRequest) {
		 CAdditionalRequest byId = cAdditionalRequestService.getById(cAdditionalRequest.getId());
		 byId.setAssignUser(cAdditionalRequest.getAssignUser());
		 cAdditionalRequestService.updateById(byId);
		 return Result.OK("编辑成功!");
	 }

	 @AutoLog(value = "增项需求表-开始报价")
	 @ApiOperation(value="增项需求表-开始报价", notes="增项需求表-开始报价")
	 @RequiresPermissions("crm:c_additional_request:edit")
	 @RequestMapping(value = "/startQuote", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> startQuote(@RequestBody CAdditionalRequest cAdditionalRequest) {
		 CAdditionalRequest byId = cAdditionalRequestService.getById(cAdditionalRequest.getId());
		 byId.setStatus("报价中");
		 cAdditionalRequestService.updateById(byId);
		 return Result.OK("编辑成功!");
	 }
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "增项需求表-通过id删除")
	@ApiOperation(value="增项需求表-通过id删除", notes="增项需求表-通过id删除")
	@RequiresPermissions("crm:c_additional_request:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		cAdditionalRequestService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "增项需求表-批量删除")
	@ApiOperation(value="增项需求表-批量删除", notes="增项需求表-批量删除")
	@RequiresPermissions("crm:c_additional_request:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.cAdditionalRequestService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "增项需求表-通过id查询")
	@ApiOperation(value="增项需求表-通过id查询", notes="增项需求表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<CAdditionalRequest> queryById(@RequestParam(name="id",required=true) String id) {
		CAdditionalRequest cAdditionalRequest = cAdditionalRequestService.getById(id);
		if(cAdditionalRequest==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(cAdditionalRequest);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param cAdditionalRequest
    */
    @RequiresPermissions("crm:c_additional_request:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CAdditionalRequest cAdditionalRequest) {
        return super.exportXls(request, cAdditionalRequest, CAdditionalRequest.class, "增项需求表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("crm:c_additional_request:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, CAdditionalRequest.class);
    }

	 @ApiOperation(value="最新一条需求", notes="最新一条需求")
	 @GetMapping(value = "/latestRequirements")
	 public Result<CAdditionalRequest> latestRequirements(@RequestParam(name="subProjectId",required=true) String subProjectId) {
		 CAdditionalRequest cAdditionalRequest = cAdditionalRequestService.latestRequirements(subProjectId);

		 return Result.OK(cAdditionalRequest);
	 }

	 @ApiOperation(value="查询数据状态数量", notes="查询数据状态数量")
	 @GetMapping(value = "/statusCount")
	 public Result<AdditionalStatusCount> statusCount(CAdditionalRequest cAdditionalRequest, HttpServletRequest req) {
		 AdditionalStatusCount additionalStatusCount = cAdditionalRequestService.statusCount(cAdditionalRequest,req);
		 return Result.OK(additionalStatusCount);
	 }



}
